import type { User } from "types/user";
import type {
  LoadingConfig,
  AdaptiveConfig,
  PaginationProps
} from "@pureadmin/table";
import { ref, onMounted, reactive } from "vue";
import { getUserPagination } from "@/api/user";
import dayjs from "dayjs";

export function useColumns(options: {
  onChangePassword?: (row: User, index: number) => void;
  onEdit?: (row: User, index: number) => void;
  onDelete?: (row: User, index: number) => void;
}) {
  const SERVER_URL = import.meta.env.VITE_SERVER_URL;
  const dataList = ref<User[]>([]);
  const loading = ref(true);
  const searchText = ref<string | undefined>(undefined);
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "id"
    },
    {
      label: "昵称",
      prop: "nickname"
    },
    {
      label: "账号",
      prop: "username"
    },
    {
      label: "头像",
      prop: "avatar",
      width: 140,
      cellRenderer: ({ row }) => {
        if (row.avatar) {
          return (
            <el-image
              style="width: 60px; height: 60px"
              src={SERVER_URL + row.avatar}
              fit="cover"
            />
          );
        }
      }
    },
    {
      label: "注册日期",
      prop: "created_on",
      width: 160,
      cellRenderer: ({ row }) => (
        <span>{dayjs(row.created_on).format("YYYY-MM-DD HH:mm:ss")}</span>
      )
    },
    {
      label: "角色",
      prop: "roles",
      width: 120,
      cellRenderer: ({ row }) => {
        if (row.roles.includes(1)) {
          return <el-tag type="danger">超级管理员</el-tag>;
        }
        return <el-tag type="primary">管理员</el-tag>;
      }
    },
    {
      label: "操作",
      width: 160,
      cellRenderer: ({ index, row }) => (
        <>
          <el-button
            size="small"
            disabled={row.roles.includes(1)}
            onClick={() => handleChnagePassword(row, index)}
          >
            修改密码
          </el-button>

          <el-popconfirm
            title="确认删除?"
            placement="top-end"
            disabled={row.roles.includes(1)}
            onConfirm={() => handleDelete(row, index)}
          >
            {{
              reference: () => (
                <el-button
                  size="small"
                  type="danger"
                  disabled={row.roles.includes(1)}
                >
                  删除
                </el-button>
              )
            }}
          </el-popconfirm>
        </>
      )
    }
  ];

  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 20,
    currentPage: 1,
    pageSizes: [20, 40, 60],
    total: 60,
    align: "right",
    background: true,
    size: "default"
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });

  /** 撑满内容区自适应高度相关配置 */
  const adaptiveConfig: AdaptiveConfig = {
    /** 表格距离页面底部的偏移量，默认值为 `96` */
    offsetBottom: 110
    /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
    // fixHeader: true
    /** 页面 `resize` 时的防抖时间，默认值为 `60` ms */
    // timeout: 60
    /** 表头的 `z-index`，默认值为 `100` */
    // zIndex: 100
  };

  async function loadData(params: {
    page: number;
    page_size: number;
    kw?: string;
  }) {
    try {
      loading.value = true;

      if (params.kw && params.kw.trim()) {
        params.kw = params.kw.trim();
      } else {
        params.kw = undefined;
      }

      const response = await getUserPagination(params);

      pagination.total = response.total;
      dataList.value = response.data;
    } catch (e) {
      console.log(e);
    } finally {
      loading.value = false;
    }
  }

  async function onSizeChange() {
    pagination.currentPage = 1;

    loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: searchText.value
    });
  }

  async function onCurrentChange() {
    loadingConfig.text = `正在加载第${pagination.currentPage}页...`;

    loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: searchText.value
    });
  }

  async function handleChnagePassword(row: User, index: number) {
    if (options.onChangePassword) {
      options.onChangePassword(row, index);
    }
  }

  async function handleDelete(row: User, index: number) {
    if (options.onDelete) {
      options.onDelete(row, index);
    }
  }

  onMounted(() => {
    loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: searchText.value
    });
  });

  async function refresh() {
    await loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: searchText.value
    });
  }

  async function search() {
    pagination.currentPage = 1;
    loadData({
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      kw: searchText.value
    });
  }

  return {
    loading,
    columns,
    dataList,
    pagination,
    loadingConfig,
    adaptiveConfig,
    searchText,
    onSizeChange,
    onCurrentChange,
    refresh,
    search
  };
}
